//
//  NetworkHelper.swift
//  SwiftLibrary
//
//  Created by wumin on 15/12/28.
//  Copyright © 2015年 taurusxi. All rights reserved.
//

import Foundation
import SwiftyJSON
import AFNetworking

class NetworkHelper {
  //  let manager:AFHTTPSessionManager
  static let shareInstance = NetworkHelper()
  
  private let taskManager:NetworkTaskManager = NetworkTaskManager.sharedInstance
  
  fileprivate init() {
    
  }
  
  
  private var networkProxy:NetworkProxyProtocol! = nil
  
  
  func configNetworkProxy(_ proxy:NetworkProxyProtocol){
    self.networkProxy = proxy
  }
  
  
  
  func addTask(_ task: NetworkTask) {
    
   
    
    guard let responceDelegate = task.responceDelegate else {
      fatalError("没有配置NetworkResponceDelegate")
    }
    
    if !NetworkConfig.isReachable() {
        TXLogError("网络异常")
        responceDelegate.handler(error: NSError.init(domain: "网络连接异常", code: 1005, userInfo: nil), AndTask: task)
      return
    }
    
    guard self.networkProxy != nil else {
      fatalError("没有配置networkProxy")
    }
    
    
    if task.needDelayFlag {
      task.callTime = CFAbsoluteTimeGetCurrent()
    }
    
    task.targetTask = self.networkProxy.handlerNetworkTask(task: task, AndSuccess: { [unowned self,unowned task](proxyResponse) in
      
      if task.needDelayFlag {
        let _ = Timer.schedule(oldTime: task.callTime, delayInterf: task.interf, handler:{
          [unowned self,unowned task] _ in
          
          guard let responceDelegate = task.responceDelegate else {
            fatalError("没有配置responceDelegate")
          }
          if responceDelegate.onfinish(task: task) {
            responceDelegate.handler(response: proxyResponse, AndTask: task)
          }
          self.taskManager.removeTask(task)
          })
        
      }else {
        guard let responceDelegate = task.responceDelegate else {
          fatalError("没有配置responceDelegate")
        }
        if responceDelegate.onfinish(task: task) {
          responceDelegate.handler(response: proxyResponse, AndTask: task)
        }
        self.taskManager.removeTask(task)
      }
    }) { [unowned task,unowned self] (error) in
      guard let responceDelegate = task.responceDelegate else {
        fatalError("没有配置responceDelegate")
      }
      if responceDelegate.onfinish(task: task) {
        responceDelegate.handler(error: error, AndTask: task)
      }
      self.taskManager.removeTask(task)
    }
    taskManager.appendTask(task)
  }
}
